package com.deer.wms.project.root.web;

import cn.hutool.core.util.ObjectUtil;
import com.deer.wms.project.root.core.result.CommonCode;
import com.deer.wms.project.root.core.result.Result;
import com.deer.wms.project.root.core.result.ResultGenerator;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * @author : wei
 * @since : 2022-03-29 13:46:25
 **/
@RestController
@RequestMapping("/common")
public class CommonController {

    @Value("${file.apk-file}")
    private String appDir;

    /**
     * 获取最新的APP的版本号，需要更新则将apk上传到服务器上再下载
     * @param oldVer 客户端请求的版本号
     * @return Result
     */
    @GetMapping("/getAppVer")
    public Result getAppVer(String oldVer) {
        String result = "";
        try {
            //Step1.进入指定下目录
            File file = new File(appDir);
            if (file.isDirectory()) {
                String[] files = file.list();
                int index = -1;
                if (ObjectUtil.isNotEmpty(files) && files.length > 0) {
                    for (int i = 0; i < files.length; i++) {
                        if (files[i].contains("apk")) {
                            index = i;
                            break;
                        }
                    }
                }
                if (index != -1) {
                    String fileName = files[index].replaceAll(".apk", "");
                    String[] verStr = fileName.split("_");
                    if (verStr.length == 2) {
                        if (!verStr[1].equals(oldVer)) {
                            result = "S:" + verStr[1];
                        } else {
                            result = "S:当前APP已经是最新版本";
                        }
                    } else {
                        result = "E:APK的文件名未带版本号";
                    }
                } else {
                    result = "E: 无更新APK文件!";
                }
            }
            if (result.contains("E:")) {
                return ResultGenerator.genFailResult(CommonCode.SERVER_INERNAL_ERROR, result);
            }
            return ResultGenerator.genSuccessResult(result);
        } catch (Exception e) {
            return ResultGenerator.genFailResult(CommonCode.SERVER_INERNAL_ERROR, e.getMessage());
        }
    }

    @GetMapping("/download/app")
    public void  downloadApp(HttpServletResponse response){
        FileInputStream fileInputStream = null;
        BufferedInputStream fis = null;
        OutputStream outputStream = null;
        try {
            // path是指想要下载的文件的路径
            File appDirFile = new File(appDir);
            String[] files = appDirFile.list();
            String fileName = "";
            if (ObjectUtil.isNotEmpty(files) && files.length > 0) {
                for (int i = 0; i < files.length; i++) {
                    if (files[i].contains("apk")) {
                        fileName = files[i];
                        break;
                    }
                }
            }
            File file = new File(appDir+"/"+fileName);
            // 将文件写入输入流
            fileInputStream = new FileInputStream(file);
            fis = new BufferedInputStream(fileInputStream);
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);

            // 清空response
            response.reset();
            // 设置response的Header
            response.setCharacterEncoding("UTF-8");
            //Content-Disposition的作用：告知浏览器以何种方式显示响应返回的文件，用浏览器打开还是以附件的形式下载到本地保存
            //attachment表示以附件方式下载 inline表示在线打开 "Content-Disposition: inline; filename=文件名.mp3"
            // filename表示文件的默认名称，因为网络传输只支持URL编码的相关支付，因此需要将文件名URL编码后进行传输,前端收到后需要反编码才能获取到真正的名称
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            // 告知浏览器文件的大小
            response.addHeader("Content-Length", "" + file.length());
            outputStream = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            outputStream.write(buffer);
            outputStream.flush();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            try {
                if (fileInputStream != null) {
                    fileInputStream.close();
                }
                if (fis != null) {
                    fis.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
